package com.example.blade.app

import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import com.blankj.utilcode.util.Utils
import java.util.*

class AppUtils2 {
    fun appsInfo(): MutableList<AppInfo2> {
        val list: MutableList<AppInfo2> = ArrayList()
        val pm = Utils.getApp().packageManager ?: return list
        val installedPackages = pm.getInstalledPackages(0)
        installedPackages.forEach {
            val ai = getBean(pm, it)
            ai?.let { it1 ->
                list.add(it1)
            }
        }
        return list
    }

    private fun getBean(pm: PackageManager, pi: PackageInfo?): AppInfo2? {
        if (pi == null) return null
        val ai = pi.applicationInfo
        val packageName = pi.packageName
        val name = ai.loadLabel(pm).toString()
        //val icon = ai.loadIcon(pm)
        val packagePath = ai.sourceDir
        //val versionName = pi.versionName
        /*val versionCode =
           if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
               pi.longVersionCode.toInt()
           } else {
               pi.versionCode
           }*/
        val isSystem = ApplicationInfo.FLAG_SYSTEM and ai.flags != 0
        return AppInfo2(packageName, name, packagePath, isSystem)
    }
}